import { message } from "ant-design-vue";
/**
 * 增删改查hook
 */
export function useCURD() {
  // 初始化数据
  const initDataHook = (request, params, data,total) => {
    request(params).then((res) => {
      data.value = res.results;
      total.value = res.count
    });
  };
  /**
   * 修改状态的钩子
   * @param title 抽屉的标题的数据
   * @param visible 抽屉是否打开的数据
   * @param status 状态
   * @param t
   * @param func
   */
  const setStatus = (visible,title, status, t, func) => {
    if (status) {
      if (func) {
        func();
      }
    }
    title.value = t;
    visible.value = status;
  };
  /**
   * 新增数据的钩子
   */
  const addDataHook = (disabled) => {
    disabled.value = false;
  };
  /**
   * 提交的钩子
   * @param form form 表单对象
   * @param isSave 是否保存
   * @param formData form数据
   * @param request 请求对象
   * @param success 成功后回调
   */
  const onSubmitHook = (form, isSave, formData, request, success) => {
    form.value.validate().then(() => {
      if (!isSave) {
        request(formData.value.id, formData.value).then((res) => {
          if (success) {
            success(res);
          }
        });
        return;
      }

      request(formData.value).then((res) => {
        if (success) {
          success();
        }
      });
    });
  };
  /**
   * 修改数据 和查看数据
   * @param row 数据行
   * @param formData 表单数据
   * @param request 请求
   * @param success 成功回调
   */
  const editDataHook = (row, formData, request, success) => {
    request(row.id).then((res) => {
      formData.value = res;
      if (success) {
        success();
      }
    });
  };
  const showDataHook = (row, formData, request, success) => {
    request(row.id).then((res) => {
      formData.value = res;
      if (success) {
        success();
      }
    });
  };
  /**
   * 删除数据
   * @param row 数据对象
   * @param request 请求对象
   */
  const delDataHook = (row, request,func) => {
    request(row.id).then((_res) => {
        if(func){
            func()
        }
    });
  };
  /**
   * 清空搜索数据
   */
  const clearSearchDataHook = (params,func) => {
    const keys = Object.keys(params);
    for (let i = 0; i < keys.length; i++) {
      const key = keys[i];
      if (key === "page" || key === "pageSize") {
        continue;
      }
      params[key] = "";
    }
    if(func){
        func()
    }
  };

  return {
    initDataHook,
    setStatus,
    addDataHook,
    onSubmitHook,
    editDataHook,
    delDataHook,
    clearSearchDataHook,
    showDataHook
  }
}